package cn.bytecollege.admin.controller;

import cn.bytecollege.admin.service.CartService;
import cn.bytecollege.admin.service.OrderDetailService;
import cn.bytecollege.admin.service.OrderService;
import cn.bytecollege.common.entity.Cart;
import cn.bytecollege.common.entity.OrderDetail;
import cn.bytecollege.common.constant.OrderIdUtils;
import lombok.SneakyThrows;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "OrderDetailAddController", value = "/admin/orderDetailAdd")
public class OrderDetailAddController extends HttpServlet {
    private OrderDetailService orderDetailService = null;
    private CartService cartService = null;
    private OrderService orderService = null;
    public OrderDetailAddController(){
        orderDetailService = new OrderDetailService();
        cartService = new CartService();
        orderService = new OrderService();
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Cart> list = cartService.find();

        if (list.size()==0){
            String msg = "购物车中无数据请添加";
            request.setAttribute("msg",msg);
            request.getRequestDispatcher(request.getContextPath()+"/admin/cartList").forward(request,response);
            return;
        }
        OrderIdUtils orderId= OrderIdUtils.getInstance();
        String nextId = orderId.nextId();
        OrderDetail orderDetail = new OrderDetail();
        //封装数据
        for (Cart c:list) {
            Integer cuisineId = c.getCuisineId();
            Integer number = c.getNumber();
            Double sellPrice = c.getCuisinePrice();
            orderDetail.setOrderNumber(nextId);
            orderDetail.setCuisineId(cuisineId);
            orderDetail.setNumber(number);
            orderDetail.setSellPrice(sellPrice);
            orderDetailService.save(orderDetail);
        }
        request.getRequestDispatcher(request.getContextPath()+"/admin/orderAdd?orderNumber="+nextId).forward(request,response);
    }
}
